class HPLOK {
    constructor() {
        // DOM元素
        this.domElements = {
            newProjectTags: document.getElementById('new-project-tags'),
            tagSuggestions: document.getElementById('tag-suggestions'),
            welcomeScreen: document.getElementById('welcome-screen'),
            projectScreen: document.getElementById('project-screen'),
            getStartedBtn: document.getElementById('get-started-btn'),
            createProjectBtn: document.getElementById('create-project-btn'),
            createProjectModal: document.getElementById('create-project-modal'),
            closeModal: document.querySelector('.close-modal'),
            cancelBtn: document.querySelector('.cancel-btn'),
            confirmCreateProject: document.getElementById('confirm-create-project'),
            newProjectName: document.getElementById('new-project-name'),
            newProjectColor: document.getElementById('new-project-color'),
            newProjectDescription: document.getElementById('new-project-description'),
            projectsList: document.getElementById('projects-list'),
            currentProjectTitle: document.getElementById('current-project-title'),
            createNoteBtn: document.getElementById('create-note-btn'),
            notesList: document.getElementById('notes-list'),
            noteTitleInput: document.getElementById('note-title-input'),
            noteContent: document.getElementById('note-content'),
            editorButtons: document.querySelectorAll('.editor-btn'),
    settingsBtn: document.getElementById('settings-btn'),
    settingsModal: document.getElementById('settings-modal'),
    borderOpacity: document.getElementById('border-opacity'),
    borderOpacityValue: document.getElementById('border-opacity-value'),
    blurAmount: document.getElementById('blur-amount'),
    blurAmountValue: document.getElementById('blur-amount-value'),
    saveSettingsBtn: document.getElementById('save-settings')
};

        // 应用状态
        this.state = {
            projects: [],
            currentProject: null,
            currentNote: null
        };

        // 初始化应用
        this.init();
    }

    // 初始化应用
    init() {
        this.loadData();
        this.loadSettings();
        this.setupEventListeners();
        this.checkForExistingProjects();
    }

    // 从localStorage加载数据
    loadData() {
        const savedProjects = localStorage.getItem('hplokProjects');
        if (savedProjects) {
            this.state.projects = JSON.parse(savedProjects);
        }
    }

    // 保存数据到localStorage
    saveData() {
        localStorage.setItem('hplokProjects', JSON.stringify(this.state.projects));
    }

    // 设置所有事件监听器
    setupEventListeners() {
        // 欢迎屏幕按钮
        this.domElements.getStartedBtn.addEventListener('click', () => this.showWelcomeScreen(false));

        // 创建项目按钮
        this.domElements.createProjectBtn.addEventListener('click', () => this.showCreateProjectModal(true));

        // 模态框关闭按钮
        this.domElements.closeModal.addEventListener('click', () => this.showCreateProjectModal(false));
        this.domElements.cancelBtn.addEventListener('click', () => this.showCreateProjectModal(false));

        // 创建项目确认
        this.domElements.confirmCreateProject.addEventListener('click', () => this.createProject());

        // 创建备忘录按钮
        this.domElements.createNoteBtn.addEventListener('click', () => this.createNote());

        // 编辑器按钮
        this.domElements.editorButtons.forEach(button => {
            button.addEventListener('click', () => this.executeEditorCommand(button.dataset.command));
        });

        // 备忘录标题和内容变化
        this.domElements.noteTitleInput.addEventListener('input', () => this.saveCurrentNote());
        this.domElements.noteContent.addEventListener('input', () => this.saveCurrentNote());

        // 标签输入事件监听
        this.domElements.newProjectTags.addEventListener('input', (e) => this.handleTagInput(e));

        // 删除备忘录按钮事件
        document.getElementById('delete-note-btn').addEventListener('click', () => this.deleteNote());
        
        // 设置模态框事件
        this.domElements.settingsBtn.addEventListener('click', () => this.showSettingsModal(true));
        this.domElements.settingsModal.querySelector('.close-modal').addEventListener('click', () => this.showSettingsModal(false));
        this.domElements.settingsModal.querySelector('.cancel-btn').addEventListener('click', () => this.showSettingsModal(false));
        this.domElements.saveSettingsBtn.addEventListener('click', () => this.saveSettings());
        
        // 滚动监听事件 - 控制液态玻璃折射效果
        let lastScrollTime = 0;
const scrollThrottleDelay = 16; // ~60fps
window.addEventListener('scroll', () => {
  const now = Date.now();
  if (now - lastScrollTime >= scrollThrottleDelay) {
    this.handleScrollEffects();
    lastScrollTime = now;
  }
}, { passive: true });
        
        // 设置滑块事件
        this.domElements.borderOpacity.addEventListener('input', (e) => {
            this.domElements.borderOpacityValue.textContent = e.target.value;
        });
        this.domElements.blurAmount.addEventListener('input', (e) => {
            this.domElements.blurAmountValue.textContent = e.target.value;
        });
    }

    // 检查是否有现有项目
    checkForExistingProjects() {
        if (this.state.projects.length > 0) {
            this.showWelcomeScreen(false);
            this.showProjectScreen(true);
            this.renderProjects();
            // 默认选择第一个项目
            this.selectProject(this.state.projects[0].id);
        }
    }

    // 显示/隐藏欢迎屏幕
    showWelcomeScreen(show) {
        this.domElements.welcomeScreen.classList.toggle('hidden', !show);
    }

    // 显示/隐藏项目屏幕
    showProjectScreen(show) {
        this.domElements.projectScreen.classList.toggle('hidden', !show);
    }

    // 显示/隐藏创建项目模态框
    showCreateProjectModal(show) {
        this.domElements.createProjectModal.classList.toggle('hidden', !show);
        if (show) {
            this.domElements.newProjectName.focus();
        } else {
            // 重置表单
            this.domElements.newProjectName.value = '';
            this.domElements.newProjectDescription.value = '';
        }
    }

    // 创建新项目
    createProject() {
        const name = this.domElements.newProjectName.value.trim();
        const color = this.domElements.newProjectColor.value;
        const description = this.domElements.newProjectDescription.value.trim();
        const tagsInput = this.domElements.newProjectTags.value.trim();
        const tags = tagsInput ? tagsInput.split(',').map(tag => tag.trim()) : [];

        if (!name) {
            alert('请输入项目名称');
            return;
        }

        const newProject = {
            id: Date.now().toString(),
            name,
            color,
            description,
            tags: tags,
            notes: []
        };

        this.state.projects.push(newProject);
        this.saveData();
        this.renderProjects();
        this.showCreateProjectModal(false);

        // 如果这是第一个项目，显示项目屏幕
        if (this.state.projects.length === 1) {
            this.showWelcomeScreen(false);
            this.showProjectScreen(true);
        }

        // 选择新创建的项目
        this.selectProject(newProject.id);
    }

    // 渲染项目列表
    renderProjects() {
        this.domElements.projectsList.innerHTML = '';

        this.state.projects.forEach(project => {
            const li = document.createElement('li');
            li.innerHTML = `
                <span class="project-color-indicator" style="background-color: ${project.color}"></span>
                <span class="project-name">${project.name}</span>
                ${project.tags && project.tags.length > 0 ? `
                <div class="project-tags">
                    ${project.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
                ` : ''}
                <button class="delete-project-btn" data-project-id="${project.id}"><i class="fas fa-times"></i></button>
            `;
            li.addEventListener('click', () => this.selectProject(project.id));
            if (this.state.currentProject && this.state.currentProject.id === project.id) {
                li.classList.add('active');
            }
            this.domElements.projectsList.appendChild(li);
        });
    }

    // 选择项目
    selectProject(projectId) {
        const project = this.state.projects.find(p => p.id === projectId);
        if (!project) return;

        this.state.currentProject = project;
        // 确保项目有notes数组
        if (!project.notes) project.notes = [];
        this.state.currentNote = project.notes.length > 0 ? project.notes[0] : null;

        // 更新UI
        this.domElements.currentProjectTitle.textContent = project.name;
        this.renderNotes();

        // 更新活动项目样式
        document.querySelectorAll('#projects-list li').forEach(li => {
            const projectNameElement = li.querySelector('.project-name');
            li.classList.toggle('active', projectNameElement && projectNameElement.textContent === project.name);
        });
    }

    // 渲染备忘录列表
    renderNotes() {
        this.domElements.notesList.innerHTML = '';

        if (!this.state.currentProject || this.state.currentProject.notes.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'notes-empty-state';
            emptyState.innerHTML = `
                <i class="fas fa-sticky-note" style="font-size: 48px; color: var(--text-secondary); margin-bottom: 15px;"></i>
                <p>该项目中暂无备忘录</p>
                <p style="font-size: 14px; color: var(--text-secondary);">点击上方"新建备忘录"按钮开始添加</p>
            `;
            this.domElements.notesList.appendChild(emptyState);
            this.clearNoteEditor();
            return;
        }

        this.state.currentProject.notes.forEach(note => {
            const noteElement = document.createElement('div');
            noteElement.className = 'note-item';
            noteElement.innerHTML = `
                <h4>${note.title || '无标题备忘录'}</h4>
                <p>${this.truncateText(note.content, 100)}</p>
                <small>${this.formatDate(note.createdAt)}</small>
            `;
            noteElement.addEventListener('click', () => this.selectNote(note.id));
            if (this.state.currentNote && this.state.currentNote.id === note.id) {
                noteElement.style.backgroundColor = 'rgba(255, 255, 255, 0.05)';
            }
            this.domElements.notesList.appendChild(noteElement);

        // 添加删除项目按钮事件监听器
        document.querySelectorAll('.delete-project-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const projectId = btn.dataset.projectId;
                this.deleteProject(projectId);
            });
        });
        });

        // 如果有选中的备忘录，加载它
        if (this.state.currentNote) {
            this.loadNoteIntoEditor(this.state.currentNote);
        } else {
            // 否则选择第一个备忘录
            this.selectNote(this.state.currentProject.notes[0].id);
        }
    }

    // 创建新备忘录
    createNote() {
        if (!this.state.currentProject) return;

        const newNote = {
            id: Date.now().toString(),
            title: '',
            content: '',
            createdAt: new Date().toISOString()
        };

        this.state.currentProject.notes.unshift(newNote); // 添加到数组开头
        this.saveData();
        this.state.currentNote = newNote;
        this.renderNotes();
        this.domElements.noteTitleInput.focus();
    }

    // 选择备忘录
    selectNote(noteId) {
        const note = this.state.currentProject.notes.find(n => n.id === noteId);
        if (!note) return;

        this.state.currentNote = note;
        this.loadNoteIntoEditor(note);

        // 更新备忘录列表选中状态
        document.querySelectorAll('.note-item').forEach(item => {
            item.style.backgroundColor = '';
        });
        event.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.05)';
    }

    // 将备忘录加载到编辑器
    loadNoteIntoEditor(note) {
        this.domElements.noteTitleInput.value = note.title || '';
        this.domElements.noteContent.innerHTML = note.content || '';
    }

    // 清空备忘录编辑器
    clearNoteEditor() {
        this.domElements.noteTitleInput.value = '';
        this.domElements.noteContent.innerHTML = '';
    }

    // 删除备忘录
    deleteNote() {
        if (!this.state.currentProject || !this.state.currentNote) return;

        if (!confirm('确定要删除这个备忘录吗？此操作无法撤销。')) return;

        // 从项目中移除备忘录
        this.state.currentProject.notes = this.state.currentProject.notes.filter(
            note => note.id !== this.state.currentNote.id
        );

        this.saveData();

        // 如果还有备忘录，选择第一个；否则清空编辑器
        if (this.state.currentProject.notes.length > 0) {
            this.state.currentNote = this.state.currentProject.notes[0];
            this.loadNoteIntoEditor(this.state.currentNote);
        } else {
            this.state.currentNote = null;
            this.clearNoteEditor();
        }

        this.renderNotes();
    }

    // 删除项目
    showSettingsModal(show) {
        this.domElements.settingsModal.classList.toggle('hidden', !show);
    }
    
    saveSettings() {
        const borderOpacity = this.domElements.borderOpacity.value;
        const blurAmount = this.domElements.blurAmount.value;
        
        document.documentElement.style.setProperty('--border-opacity', borderOpacity);
        document.documentElement.style.setProperty('--blur-amount', `${blurAmount}px`);
        
        localStorage.setItem('hplokSettings', JSON.stringify({
            borderOpacity,
            blurAmount
        }));
        
        this.showSettingsModal(false);
    }
    
    handleScrollEffects() {
    if (!this.isScrolling) {
      requestAnimationFrame(() => {
        this.updateReflectionStyles();
        this.isScrolling = false;
      });
    }
    this.isScrolling = true;
  }

  updateReflectionStyles() {
        // 获取滚动位置百分比
        const scrollY = window.scrollY;
        const documentHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);
        const windowHeight = window.innerHeight;
        const scrollableHeight = documentHeight - windowHeight;
        const scrollPercent = scrollableHeight > 0 ? (scrollY / scrollableHeight) * 100 : 0;
        
        // 计算反射位置 (-50% 到 50% 之间)
        const reflectionPosition = -50 + (scrollPercent / 2);
        
        // 计算反射角度 (-35deg 到 -15deg 之间)
        const reflectionAngle = -30 + (scrollPercent / 20);
        
        // 更新CSS变量
        document.documentElement.style.setProperty('--reflection-position', `${reflectionPosition}%`);
        document.documentElement.style.setProperty('--reflection-angle', `${reflectionAngle}deg`);
    }
    
    loadSettings() {
        const savedSettings = localStorage.getItem('hplokSettings');
        if (savedSettings) {
            const { borderOpacity, blurAmount } = JSON.parse(savedSettings);
            this.domElements.borderOpacity.value = borderOpacity;
            this.domElements.borderOpacityValue.textContent = borderOpacity;
            this.domElements.blurAmount.value = blurAmount;
            this.domElements.blurAmountValue.textContent = blurAmount;
            
            document.documentElement.style.setProperty('--border-opacity', borderOpacity);
            document.documentElement.style.setProperty('--blur-amount', `${blurAmount}px`);
        }
    }
    
    deleteProject(projectId) {
        if (!confirm('确定要删除这个项目吗？所有相关备忘录也将被删除，此操作无法撤销。')) return;

        // 从项目列表中移除项目
        this.state.projects = this.state.projects.filter(project => project.id !== projectId);

        this.saveData();

        // 如果删除的是当前项目
        if (this.state.currentProject && this.state.currentProject.id === projectId) {
            this.state.currentProject = null;
            this.state.currentNote = null;
            this.clearNoteEditor();

            // 如果还有项目，选择第一个；否则显示欢迎屏幕
            if (this.state.projects.length > 0) {
                this.selectProject(this.state.projects[0].id);
            } else {
                this.showProjectScreen(false);
                this.showWelcomeScreen(true);
            }
        }

        this.renderProjects();
    }

    // 处理标签输入并生成建议
    handleTagInput(e) {
        const input = e.target.value.trim();
        const suggestionsContainer = this.domElements.tagSuggestions;
        suggestionsContainer.innerHTML = '';

        if (!input) return;

        // 提取所有现有标签
        const allTags = this.state.projects.reduce((tags, project) => {
            if (project.tags) {
                tags.push(...project.tags);
            }
            return tags;
        }, []);

        // 去重并筛选匹配的标签
        const uniqueTags = [...new Set(allTags)];
        const matchingTags = uniqueTags.filter(tag => 
            tag.toLowerCase().includes(input.toLowerCase()) && 
            !input.split(',').map(t => t.trim()).includes(tag)
        ).slice(0, 5);

        // 显示建议
        if (matchingTags.length > 0) {
            matchingTags.forEach(tag => {
                const suggestion = document.createElement('div');
                suggestion.className = 'tag-suggestion';
                suggestion.textContent = tag;
                suggestion.addEventListener('click', () => {
                    const currentValue = this.domElements.newProjectTags.value;
                    const trimmedValue = currentValue.trim();
                    
                    if (trimmedValue.endsWith(',')) {
                        this.domElements.newProjectTags.value = trimmedValue + ' ' + tag + ', ';
                    } else if (trimmedValue.includes(',')) {
                        this.domElements.newProjectTags.value = trimmedValue + ', ' + tag;
                    } else {
                        this.domElements.newProjectTags.value = tag + ', ';
                    }
                    this.domElements.newProjectTags.focus();
                    suggestionsContainer.innerHTML = '';
                });
                suggestionsContainer.appendChild(suggestion);
            });
        }
    }

    // 保存当前备忘录
    saveCurrentNote() {
        if (!this.state.currentNote) return;

        this.state.currentNote.title = this.domElements.noteTitleInput.value.trim();
        this.state.currentNote.content = this.domElements.noteContent.innerHTML;
        this.state.currentNote.updatedAt = new Date().toISOString();

        this.saveData();
        this.renderNotes();
    }

    // 执行编辑器命令
    executeEditorCommand(command) {
        switch(command) {
            case 'createLink':
                const url = prompt('请输入链接地址:');
                if (url) {
                    document.execCommand(command, false, url);
                }
                break;
            case 'insertImage':
                const imageUrl = prompt('请输入图片URL:');
                if (imageUrl) {
                    document.execCommand(command, false, imageUrl);
                }
                break;
            default:
                document.execCommand(command, false, null);
        }
        this.domElements.noteContent.focus();
    }

    // 辅助函数：截断文本
    truncateText(text, maxLength) {
        if (!text) return '';
        const plainText = text.replace(/<[^>]*>?/gm, ''); // 移除HTML标签
        return plainText.length > maxLength ? plainText.substring(0, maxLength) + '...' : plainText;
    }

    // 辅助函数：格式化日期
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }
}

// 当DOM加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new HPLOK();
});